package cn.com.cfae.iras.doc.analyze.pdf.writer;

import cn.com.cfae.iras.doc.analyze.pdf.Cell;
import cn.com.cfae.iras.doc.analyze.pdf.RectangularTextContainer;
import cn.com.cfae.iras.doc.analyze.pdf.Table;
import cn.com.cfae.iras.doc.analyze.pdf.TextChunk;
import cn.com.cfae.iras.doc.analyze.pdf.json.RectangularTextContainerSerializer;
import cn.com.cfae.iras.doc.analyze.pdf.json.TableSerializer;
import com.google.gson.*;

import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.List;

public class JSONWriter extends AbstractWriter {

    private static final ExclusionStrategy ALLCLASSES_SKIPNONPUBLIC = new ExclusionStrategy() {
        @Override
        public boolean shouldSkipClass(Class<?> c) {
            return false;
        }

        @Override
        public boolean shouldSkipField(FieldAttributes fa) {
            return !fa.hasModifier(Modifier.PUBLIC);
        }
    };


    @Override
    public String write(Table table) throws IOException {

        return gson().toJson(table, Table.class);


    }

    @Override
    public String write(List<Table> tables) throws IOException {
        Gson gson = gson();
        JsonArray array = new JsonArray();
        for (Table table : tables) array.add(gson.toJsonTree(table, Table.class));
        return gson.toJson(array);
    }

    @Override
    public void write(Appendable out, Table table) throws IOException {
        out.append(gson().toJson(table, Table.class));
    }

    @Override
    public void write(Appendable out, List<Table> tables) throws IOException {
        Gson gson = gson();
        JsonArray array = new JsonArray();
        for (Table table : tables) array.add(gson.toJsonTree(table, Table.class));
        out.append(gson.toJson(array));
    }

    private static Gson gson() {
        return new GsonBuilder()
                .addSerializationExclusionStrategy(ALLCLASSES_SKIPNONPUBLIC)
                .registerTypeAdapter(Table.class, TableSerializer.INSTANCE)
                .registerTypeAdapter(RectangularTextContainer.class, RectangularTextContainerSerializer.INSTANCE)
                .registerTypeAdapter(Cell.class, RectangularTextContainerSerializer.INSTANCE)
                .registerTypeAdapter(TextChunk.class, RectangularTextContainerSerializer.INSTANCE)
                .create();
    }

}
